﻿package 
{
    import MainGame.*;
    import Message.DB.Tables.*;
    import baseEngine.system.*;
    import com.gengine.debug.*;
    import com.gengine.game.*;
    import com.gengine.global.*;
    import com.gengine.manager.*;
    import com.gengine.resource.*;
    import com.gengine.resource.core.*;
    import com.gengine.resource.info.*;
    import com.gengine.resource.loader.*;
    import com.gengine.ui.*;
    import com.gengine.utils.*;
    import com.mui.controls.*;
    import com.mui.core.*;
    import com.mui.events.*;
    import com.mui.manager.*;
    import com.mui.utils.*;
    import extend.js.*;
    import extend.language.*;
    import extend.php.*;
    import flash.display.*;
    import flash.events.*;
    import flash.net.*;
    import flash.system.*;
    import flash.utils.*;
    import frEngine.event.*;
    import frEngine.loaders.resource.info.*;
    import frEngine.manager.*;
    import mortal.common.*;
    import mortal.common.display.*;
    import mortal.common.font.*;
    import mortal.common.global.*;
    import mortal.common.preLoadPage.*;
    import mortal.component.skin.*;
    import mortal.component.window.*;
    import mortal.game.*;
    import mortal.game.control.*;
    import mortal.game.manager.*;
    import mortal.game.mvc.*;
    import mortal.game.resource.*;
    import mortal.game.resource.tableConfig.*;
    import mortal.game.scene3D.*;
    import mortal.game.scene3D.display3d.icon3d.*;
    import mortal.game.scene3D.map3D.*;
    import mortal.game.scene3D.player.type.*;
    import mortal.game.scene3D.util.*;
    import mortal.game.view.chat.selectPanel.*;
    import mortal.game.view.common.alertwins.*;
    import mortal.game.view.common.tooltip.*;

    public class MainGame extends Application
    {
        private var _libraryUrls:Array;
        private var _isLoadModelFail:Boolean = false;
        private var _meshByteLoaded:Number = 0;
        private var _meshByteTotal:Number = 1;
        private var _textureByteLoaded:Number = 0;
        private var _textureByteTotal:Number = 1;
        private var _boneByteLoaded:Number = 0;
        private var _boneByteTotal:Number = 1;
        private var _isMeshLoaded:Boolean = false;
        private var _isTextureLoaded:Boolean = false;
        private var _isBoneLoaded:Boolean = false;
        private var _hairMeshByteLoaded:Number = 0;
        private var _hairMeshByteTotal:Number = 1;
        private var _hairTextureByteLoaded:Number = 0;
        private var _hairTextureByteTotal:Number = 1;
        private var _hairBoneByteLoaded:Number = 0;
        private var _hairBoneByteTotal:Number = 1;
        private var _isHairMeshLoaded:Boolean = false;
        private var _isHairTextureLoaded:Boolean = false;
        private var _isHairBoneLoaded:Boolean = false;
        private var _urlLoader:URLLoader;
        private var _isEnter:Boolean = false;

        public function MainGame()
        {
            this._libraryUrls = ["assets/uifla/imageLib.swf"];
            return;
        }// end function

        override protected function initApp(event:Event = null) : void
        {
            super.initApp(event);
            Log.debug("initApp");
            GameGlobal.mouseBtnOutFunction = this.setNormalCursor;
            GameGlobal.mousebtnInFunction = this.setButtonCursor;
            UICompomentPool.clientDisposeFun = this.mortalDisposeUI;
            MoveUtil.init();
            CacheManager.instance.initCache();
            FontUtil.init();
            this.initLoaderParams();
            JSASSender.instance.start();
            SceneRange.screenResolutionX = Capabilities.screenResolutionX;
            SceneRange.screenResolutionY = Capabilities.screenResolutionY;
            StreamManager.init();
            ParamsConst.instance.init(stage);
            this.stage.scaleMode = StageScaleMode.NO_SCALE;
            this.stage.align = StageAlign.TOP_LEFT;
            this.stage.tabChildren = false;
            this.stage.stageFocusRect = false;
            if (ParamsConst.Delay)
            {
                setTimeout(this.initConfig, ParamsConst.Delay);
            }
            else
            {
                this.initConfig();
            }
            return;
        }// end function

        private function initLoaderParams() : void
        {
            FileType.addClassRef(".MESH", DataLoader, MeshInfo);
            FileType.addClassRef(".MD5MESH", DataLoader, Md5MeshInfo);
            FileType.addClassRef(".PARTICLE", DataLoader, ParticleInfo);
            FileType.addClassRef(".SKELETON", DataLoader, SkeletonInfo);
            FileType.addClassRef(".EFFECT", DataLoader, EffectInfo);
            return;
        }// end function

        private function onClearCacheHandler() : void
        {
            CacheManager.instance.clear();
            return;
        }// end function

        private function initConfig() : void
        {
            Log.system("开始加载配置文件", "系统总内存:", System.totalMemory);
            ConfigManager.instance.addEventListener(Event.COMPLETE, this.onConfigCompleteHandler);
            ConfigManager.instance.addEventListener(ProgressEvent.PROGRESS, this.configLoadProgressHandler);
            ConfigManager.instance.addEventListener(ErrorEvent.ERROR, this.onConfigErrorHandler);
            ConfigManager.instance.addEventListener(IOErrorEvent.IO_ERROR, this.onIOErrorHandler);
            ConfigManager.instance.load(PathConst.configUrl);
            return;
        }// end function

        private function configLoadProgressHandler(event:ProgressEvent) : void
        {
            this.setProgress(PreloaderConfig.LOAD_CONFIG, event.bytesLoaded, event.bytesTotal);
            return;
        }// end function

        private function onConfigErrorHandler(event:ErrorEvent) : void
        {
            if (PHPSender.isCreateRole)
            {
                PHPSender.sendToURLByPHP(SenderType.LoadConfigFail, event.text);
            }
            return;
        }// end function

        private function onIOErrorHandler(event:Event) : void
        {
            ConfigManager.instance.load(PathConst.configUrl + Math.random());
            return;
        }// end function

        private function onConfigCompleteHandler(event:Event) : void
        {
            ConfigManager.instance.removeEventListener(Event.COMPLETE, this.onConfigCompleteHandler);
            ConfigManager.instance.removeEventListener(ProgressEvent.PROGRESS, this.configLoadProgressHandler);
            ConfigManager.instance.removeEventListener(ErrorEvent.ERROR, this.onConfigErrorHandler);
            ConfigManager.instance.removeEventListener(IOErrorEvent.IO_ERROR, this.onIOErrorHandler);
            if (PHPSender.isCreateRole)
            {
                PHPSender.sendToURLByPHP(SenderType.LoadConfigSuccess);
                if (ParamsConst.instance.preloaders != null && ParamsConst.instance.preloaders != "")
                {
                    PreloaderConfig.preResUrl = ParamsConst.instance.preloaders.split(",");
                    if (PreloaderConfig.preResUrl != null && PreloaderConfig.preResUrl.length > 0)
                    {
                        this._libraryUrls = this._libraryUrls.concat(PreloaderConfig.preResUrl);
                    }
                }
            }
            LoaderHelp.setGetPath(this.setGetResPath);
            Resource3dKilAlpha.instance.init();
            BlendTypeConfig.instance.init();
            Icon3DFactory.instance.config();
            if (ParamsConst.instance.gameName == null)
            {
                ParamsConst.instance.gameName = "风暴大陆";
            }
            ResManager.instance.loadFont();
            Log.system("开始加载素材文件", "系统总内存:", System.totalMemory);
            if (!Global.isDebugModle)
            {
                JSASSender.instance.addCloseHandler();
            }
            Alert.okLabelDefault = Language.getString(10015);
            Alert.calcelLabelDefault = Language.getString(10016);
            Alert.yesLabelDefault = Language.getString(10017);
            Alert.noLabelDefault = Language.getString(10018);
            Alert.checkBoxLabelDefault = Language.getString(10019);
            Alert.okLabel = Alert.okLabelDefault;
            Alert.calcelLabel = Alert.calcelLabelDefault;
            Alert.yesLabel = Alert.yesLabelDefault;
            Alert.noLabel = Alert.noLabelDefault;
            Alert.checkBoxLabel = Alert.checkBoxLabelDefault;
            TimerTest.tipText = "检测到使用加速器，\n请刷新后再进行游戏";
            GlobalClass.libaray.addEventListener(LibraryEvent.LOAD_COMPLETE, this.onlibraryCompleteHandler);
            GlobalClass.libaray.addEventListener(ProgressEvent.PROGRESS, this.resourceLoadProgressHandler);
            GlobalClass.libaray.addEventListener(ErrorEvent.ERROR, this.onLibraryErrorHandler);
            Game.scene = new GameScene3D(Global.application);
            Global3D.scene = Game.scene;
            if (Game.scene.context)
            {
                this.startLoadSwf(null);
            }
            else
            {
                FrEventDispatcher.instance.proxyAddEventListener(Game.scene, Event.CONTEXT3D_CREATE, this.startLoadSwf);
            }
            return;
        }// end function

        private function startLoadSwf(event:Event) : void
        {
            var _loc_3:String = null;
            FrEventDispatcher.instance.proxyRemoveEventListener(Game.scene, Event.CONTEXT3D_CREATE, this.startLoadSwf);
            Program3dManager.instance.init();
            var _loc_2:int = 0;
            while (_loc_2 < this._libraryUrls.length)
            {
                
                _loc_3 = PathConst.mainPath + this._libraryUrls[_loc_2] + "?v=" + ParamsConst.instance.resTime;
                GlobalClass.libaray.loadSWF(_loc_3, "", true);
                _loc_2++;
            }
            return;
        }// end function

        private function onLibraryErrorHandler(event:ErrorEvent) : void
        {
            if (PHPSender.isCreateRole)
            {
                PHPSender.sendToURLByPHP(SenderType.LoadResourceFail, event.text);
            }
            return;
        }// end function

        private function resourceLoadProgressHandler(event:ProgressEvent) : void
        {
            this.setProgress(PreloaderConfig.LOAD_RESCOUSE, event.bytesLoaded, event.bytesTotal);
            return;
        }// end function

        private function onlibraryCompleteHandler(event:LibraryEvent) : void
        {
            Log.system("像素文件加载完毕", "系统总内存:", System.totalMemory);
            BitmapDataConst.registToGlobal();
            GlobalSkin.initStyleSkin();
            if (PHPSender.isCreateRole)
            {
                PHPSender.sendToURLByPHP(SenderType.LoadResourceSuccess);
            }
            this.removeLoadListeners();
            if (PreLoginProxy.instance.isLoginSuccess)
            {
                this.loadRole();
            }
            else if (PreloaderCache.isMultipleRole)
            {
                PreLoginProxy.instance.addEventListener(PreLoginProxy.LOGIN_SUCCESS, this.multipleLoginSuccessHandler);
                LoginController.instance.showRoleSelectPage();
            }
            else
            {
                PreLoginProxy.instance.addEventListener(PreLoginProxy.LOGIN_SUCCESS, this.preLoginSuccessHandler);
            }
            return;
        }// end function

        private function multipleLoginSuccessHandler(event:Event) : void
        {
            PreLoginProxy.instance.removeEventListener(PreLoginProxy.LOGIN_SUCCESS, this.multipleLoginSuccessHandler);
            LoginController.instance.hideRoleSelectPage();
            this.loadRole();
            return;
        }// end function

        private function preLoginSuccessHandler(event:Event) : void
        {
            PreLoginProxy.instance.removeEventListener(PreLoginProxy.LOGIN_SUCCESS, this.preLoginSuccessHandler);
            this.setProgress(PreloaderConfig.LOAD_RESCOUSE, 100, 100);
            this.loadRole();
            return;
        }// end function

        private function loadRole() : void
        {
            var _loc_2:String = null;
            var _loc_3:String = null;
            var _loc_4:String = null;
            var _loc_1:* = PlayerModelConfig.instance.getModelInfo(ModelType.CLOTHES, 0, PreLoginProxy.instance.sloginReturn.sex, PreLoginProxy.instance.sloginReturn.career);
            if (_loc_1)
            {
                _loc_2 = _loc_1.mesh + ".md5mesh";
                _loc_3 = _loc_1.texture;
                _loc_4 = _loc_1.bone + ".skeleton";
                LoaderManager.instance.load(_loc_2, this.onMeshLoaded, LoaderPriority.LevelA, null, this.onMeshProgress, this.onModelFail);
                LoaderManager.instance.load(_loc_3, this.onTextureLoaded, LoaderPriority.LevelA, null, this.onTextureProgress, this.onModelFail);
                LoaderManager.instance.load(_loc_4, this.onBoneLoaded, LoaderPriority.LevelA, null, this.onBoneProgress, this.onModelFail);
                _loc_1 = PlayerModelConfig.instance.getModelInfo(ModelType.HAIR, 0, PreLoginProxy.instance.sloginReturn.sex, PreLoginProxy.instance.sloginReturn.career);
                if (_loc_1)
                {
                    _loc_2 = _loc_1.mesh + ".md5mesh";
                    _loc_3 = _loc_1.texture;
                    _loc_4 = _loc_1.bone + ".skeleton";
                    LoaderManager.instance.load(_loc_2, this.onHairMeshLoaded, LoaderPriority.LevelA, null, this.onHairMeshProgress, this.onModelFail);
                    LoaderManager.instance.load(_loc_3, this.onHairTextureLoaded, LoaderPriority.LevelA, null, this.onHairTextureProgress, this.onModelFail);
                    LoaderManager.instance.load(_loc_4, this.onHairBoneLoaded, LoaderPriority.LevelA, null, this.onHairBoneProgress, this.onModelFail);
                }
            }
            else
            {
                this.loadVideo();
            }
            return;
        }// end function

        private function onModelFail(param1:ResourceInfo) : void
        {
            if (param1)
            {
                PHPSender.sendToURLByPHP(SenderType.LoadRoleModelFail, param1.path);
            }
            this._isLoadModelFail = true;
            this.loadVideo();
            return;
        }// end function

        private function onMeshLoaded(param1:ResourceInfo) : void
        {
            this._isMeshLoaded = true;
            this.checkLoadRole();
            return;
        }// end function

        private function onTextureLoaded(param1:ResourceInfo) : void
        {
            this._isTextureLoaded = true;
            this.checkLoadRole();
            return;
        }// end function

        private function onBoneLoaded(param1:ResourceInfo) : void
        {
            this._isBoneLoaded = true;
            this.checkLoadRole();
            return;
        }// end function

        private function onMeshProgress(event:ProgressEvent) : void
        {
            this._meshByteLoaded = event.bytesLoaded;
            this._meshByteTotal = event.bytesTotal;
            this.updateLoadRoleProgress();
            return;
        }// end function

        private function onTextureProgress(event:ProgressEvent) : void
        {
            this._textureByteLoaded = event.bytesLoaded;
            this._textureByteTotal = event.bytesTotal;
            this.updateLoadRoleProgress();
            return;
        }// end function

        private function onBoneProgress(event:ProgressEvent) : void
        {
            this._boneByteLoaded = event.bytesLoaded;
            this._boneByteTotal = event.bytesTotal;
            this.updateLoadRoleProgress();
            return;
        }// end function

        private function onHairMeshLoaded(param1:ResourceInfo) : void
        {
            this._isHairMeshLoaded = true;
            this.checkLoadRole();
            return;
        }// end function

        private function onHairTextureLoaded(param1:ResourceInfo) : void
        {
            this._isHairTextureLoaded = true;
            this.checkLoadRole();
            return;
        }// end function

        private function onHairBoneLoaded(param1:ResourceInfo) : void
        {
            this._isHairBoneLoaded = true;
            this.checkLoadRole();
            return;
        }// end function

        private function onHairMeshProgress(event:ProgressEvent) : void
        {
            this._hairMeshByteLoaded = event.bytesLoaded;
            this._hairMeshByteTotal = event.bytesTotal;
            this.updateLoadRoleProgress();
            return;
        }// end function

        private function onHairTextureProgress(event:ProgressEvent) : void
        {
            this._hairTextureByteLoaded = event.bytesLoaded;
            this._hairTextureByteTotal = event.bytesTotal;
            this.updateLoadRoleProgress();
            return;
        }// end function

        private function onHairBoneProgress(event:ProgressEvent) : void
        {
            this._hairBoneByteLoaded = event.bytesLoaded;
            this._hairBoneByteTotal = event.bytesTotal;
            this.updateLoadRoleProgress();
            return;
        }// end function

        private function checkLoadRole() : void
        {
            if (this._isMeshLoaded && this._isTextureLoaded && this._isBoneLoaded && this._isHairMeshLoaded && this._isHairTextureLoaded && this._isHairBoneLoaded)
            {
                PHPSender.sendToURLByPHP(SenderType.LoadRoleModelSuccess);
                this.loadVideo();
            }
            return;
        }// end function

        private function updateLoadRoleProgress() : void
        {
            if (this._isLoadModelFail)
            {
                return;
            }
            var _loc_1:Number = 10;
            var _loc_2:Number = 10;
            var _loc_3:Number = 50;
            var _loc_4:Number = 10;
            var _loc_5:Number = 10;
            var _loc_6:Number = 10;
            var _loc_7:* = (this._isMeshLoaded ? (_loc_1) : (_loc_1 * this._meshByteLoaded / this._meshByteTotal)) + (this._isTextureLoaded ? (_loc_2) : (_loc_2 * this._textureByteLoaded / this._textureByteTotal)) + (this._isBoneLoaded ? (_loc_3) : (_loc_3 * this._boneByteLoaded / this._boneByteTotal)) + (this._isHairMeshLoaded ? (_loc_4) : (_loc_4 * this._meshByteLoaded / this._meshByteTotal)) + (this._isHairTextureLoaded ? (_loc_5) : (_loc_5 * this._textureByteLoaded / this._textureByteTotal)) + (this._isHairBoneLoaded ? (_loc_6) : (_loc_6 * this._boneByteLoaded / this._boneByteTotal));
            this.setProgress(PreloaderConfig.LOAD_ROLE, _loc_7, 100);
            return;
        }// end function

        private function loadVideo() : void
        {
            var _loc_2:Array = null;
            var _loc_3:TPlayerModel = null;
            var _loc_4:String = null;
            var _loc_5:int = 0;
            if (this._isEnter)
            {
                return;
            }
            this._isEnter = true;
            if (ParamsConst.instance.newUser)
            {
                LoaderManager.instance.load("WelcomeBg.swf", this.onPreLoaded, LoaderPriority.LevelA);
                LoaderManager.instance.load("WelComeEnterGameBtn.swf", this.onPreLoaded, LoaderPriority.LevelA);
                _loc_2 = ["skill21", "skill22", "skill23", "stand", "run", "jump", "fightwait", "fightrun", "skill08", "skill07"];
                _loc_3 = PlayerModelConfig.instance.getModelInfo(ModelType.CLOTHES, 0, PreLoginProxy.instance.sloginReturn.sex, PreLoginProxy.instance.sloginReturn.career);
                if (_loc_3)
                {
                    _loc_4 = _loc_3.bone;
                    _loc_5 = 0;
                    while (_loc_5 < _loc_2.length)
                    {
                        
                        LoaderManager.instance.load(_loc_4 + "___" + _loc_2[_loc_5] + ".data", this.onPreLoaded, LoaderPriority.LevelA);
                        _loc_5++;
                    }
                }
                LoaderManager.instance.load("DiverTip.swf", this.onPreLoaded, LoaderPriority.LevelA);
                LoaderManager.instance.load("zc_zylx2.abc", this.onPreLoaded, LoaderPriority.LevelA);
                LoaderManager.instance.load("zc_fgnpc5.abc", this.onPreLoaded, LoaderPriority.LevelA);
                LoaderManager.instance.load("q30gw_ymkl.abc", this.onPreLoaded, LoaderPriority.LevelA);
                LoaderManager.instance.load("xsc_bb1.abc", this.onPreLoaded, LoaderPriority.LevelA);
                LoaderManager.instance.load("qb1.abc", this.onPreLoaded, LoaderPriority.LevelA);
            }
            var _loc_1:* = new Timer(20, 80);
            _loc_1.addEventListener(TimerEvent.TIMER, this.onTimer);
            _loc_1.addEventListener(TimerEvent.TIMER_COMPLETE, this.onTimerComplete);
            _loc_1.start();
            this.loginReady();
            return;
        }// end function

        private function onTimer(event:TimerEvent) : void
        {
            var _loc_2:* = event.target as Timer;
            this.setProgress(PreloaderConfig.LOAD_VIDEO, _loc_2.currentCount, _loc_2.repeatCount);
            return;
        }// end function

        private function onTimerComplete(event:TimerEvent) : void
        {
            var _loc_2:* = event.target as Timer;
            this.setProgress(PreloaderConfig.LOAD_VIDEO, 100, 100);
            _loc_2.stop();
            GameState.isGameLoadCompl = true;
            if (GameState.isLoginInCompl)
            {
                GameLoadBar.instance.hide();
            }
            return;
        }// end function

        private function onPreLoaded(param1) : void
        {
            return;
        }// end function

        private function onVideoCompleteHandler() : void
        {
            this.setProgress(PreloaderConfig.LOAD_VIDEO, 100, 100);
            this._urlLoader = null;
            this.loginReady();
            return;
        }// end function

        private function onVideoProgressHandler(event:ProgressEvent) : void
        {
            this.setProgress(PreloaderConfig.LOAD_VIDEO, event.bytesLoaded, event.bytesTotal);
            return;
        }// end function

        private function onVideoIOError(event:Event) : void
        {
            this.setProgress(PreloaderConfig.LOAD_VIDEO, 100, 100);
            this._urlLoader = null;
            this.loginReady();
            return;
        }// end function

        private function removeVideoEvent() : void
        {
            this._urlLoader.removeEventListener(Event.COMPLETE, this.onVideoCompleteHandler);
            this._urlLoader.removeEventListener(ProgressEvent.PROGRESS, this.onVideoProgressHandler);
            this._urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, this.onVideoIOError);
            this._urlLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onVideoIOError);
            return;
        }// end function

        private function loginReady() : void
        {
            this.startGame();
            return;
        }// end function

        private function startGame() : void
        {
            LayerManager.init();
            WindowLayer.topLayerChangeHander = LayerManager.setWindowLayerTop;
            ToolTipsManager.init(LayerManager.toolTipLayer);
            ToolTipsManager.defaultRenderClass = Tooltip;
            DragManager.init(LayerManager.dragLayer);
            Alert.init(LayerManager.alertLayer);
            Alert.defaultAlertWinRenderer = CustomAlertWin;
            if (Global.isDebugModle)
            {
                Global.application.addChild(FPS.instance);
                GameManager.instance.init();
            }
            else
            {
                FPS.instance.initTimer();
            }
            Log.system("Alert Drag toolTip初始化完毕", "系统总内存:", System.totalMemory);
            GameController.init();
            StageMouseManager.instance.start();
            Log.system("控制器初始化完毕", "系统总内存:", System.totalMemory);
            Log.system("皮肤初始化完毕", "系统总内存:", System.totalMemory);
            Log.debugLog = DebugWindow.instance;
            GameLoadBar.instance.isGameLoadComplete = true;
            Log.system("准备登陆游戏", "系统总内存:", System.totalMemory);
            LoginController.instance.loadGame();
            return;
        }// end function

        private function removeLoadListeners() : void
        {
            GlobalClass.libaray.removeEventListener(LibraryEvent.LOAD_COMPLETE, this.onlibraryCompleteHandler);
            GlobalClass.libaray.removeEventListener(ProgressEvent.PROGRESS, this.resourceLoadProgressHandler);
            GlobalClass.libaray.removeEventListener(ErrorEvent.ERROR, this.onLibraryErrorHandler);
            return;
        }// end function

        private function setProgress(param1:int, param2:Number, param3:Number) : void
        {
            GameLoadBar.instance.setProgress(param1, param2, param3);
            return;
        }// end function

        private function setGetResPath(param1:String) : String
        {
            param1 = GImageBitmap.getUrl(param1);
            var _loc_2:* = ResConfig.instance.getInfoByName(param1);
            if (_loc_2)
            {
                return _loc_2.path;
            }
            Log.debug("LoaderHelp找不到资源路径：" + param1);
            return PathConst.mainPath + "assets/uifla/button/" + param1 + "?v=";
        }// end function

        private function mortalDisposeUI(param1:DisplayObject) : void
        {
            EffectManager.glowFilterUnReg(param1);
            if (param1 is IFrUI)
            {
                FacePanel.unRegistBtn(param1 as IFrUI);
            }
            return;
        }// end function

        private function setNormalCursor() : void
        {
            CursorManager.hideFromButton();
            return;
        }// end function

        private function setButtonCursor() : void
        {
            CursorManager.showCursor(CursorManager.BUTTON);
            return;
        }// end function

    }
}
